package com.yang.service;

import com.yang.dao.MenuDao;
import com.yang.pojo.Menu1;
import com.yang.pojo.Menu2;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MenuService {
    /**
     * 根据管理员id查询当前管理员菜单列表（一级菜单需要包含对应的二级菜单）
     */

    MenuDao menuDao = new MenuDao();
    public ArrayList<Menu1> listMenuById(String mgrId) throws SQLException {

        
        //1、根据id查询一级菜单的列表
        ArrayList<Menu1> menu1List = menuDao.selectFirstLevelMenuByMgrId(mgrId);
        for (int i = 0; i < menu1List.size(); i++) {
            Menu1 menu1 = menu1List.get(i);
            //查询每个一级菜单列表中的二级菜单
            ArrayList<Menu2> menu2List = menuDao.selectSecondLevelMenuByMgrIdAndParentCode(mgrId, menu1.getMenuCode());
            //将二级菜单集合，设置给一级菜单对象
            menu1.setChildMenus(menu2List);
        }
        return menu1List;
    }

    //同时返回一级和二级菜单
    public Map<String,List> listMenus() throws SQLException {
        HashMap<String, List> menus = new HashMap<>();
        //查询一级菜单
        ArrayList<Menu1> menu1List = menuDao.selectMenu1();
        //查询二级菜单
        ArrayList<Menu2> menu2List = menuDao.selectMenu2();
        //将menu1List和menu2List存储到map中
        menus.put("menu1List",menu1List);
        menus.put("menu2List",menu2List);
        return menus;
    }

    //根据一级菜单查询二级菜单
    public ArrayList<Menu2> selectMnu2ByMenu1Code(String menuParentCode) throws SQLException {
        ArrayList<Menu2> menu2List = menuDao.selectMenu2ByMenu1(menuParentCode);
        return menu2List;
    }

    //启用
    public boolean enableMenu(String menuCode) throws SQLException {
        return changeMenuCode(menuCode,1);
    }

    //停用
    public boolean disableMenu(String menuCode) throws SQLException {
        return changeMenuCode(menuCode,0);
    }

    private boolean changeMenuCode(String menuCode,int state) throws SQLException {
        int i = menuDao.updateMenuState(menuCode, state);
        boolean b = i>0;
        return b;

    }

    /**
     * 查询所有的一级菜单，并且在每一个一级菜单中红包含其对应的二级菜单
     */
    public ArrayList<Menu1> listAllMenu() throws SQLException {
        ArrayList<Menu1> menu1s = menuDao.selectMenu1();
        //遍历menus拿到menuCode，依次查询二级菜单
        for (int i = 0; i < menu1s.size(); i++) {
            Menu1 menu1 = menu1s.get(i);
            //根据一级菜单的menuCode查询二级菜单
            ArrayList<Menu2> menu2s = menuDao.selectMenu2ByMenu1(menu1.getMenuCode());
            //将menu2s作为menu1s的子类
            menu1.setChildMenus(menu2s);
        }
        return menu1s;
    }
}
